package com.xiaoyun.alllearning.exception;

import com.xiaoyun.alllearning.domain.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult businessExceptionHandler(BusinessException e) {

        log.info("捕获到运行时异常 businessExceptionHandler:{}", e);
        return ResponseResult.failure(e.getCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    protected ResponseResult methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        StringBuilder messageSb = new StringBuilder();
        ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .forEach(item -> {
                    messageSb.append(item);
                });
        String message = messageSb.toString();
        log.info("捕获到运行时异常 methodArgumentNotValidException:{}", message);
        return ResponseResult.failure(ErrorCodeEnum.PARAM_ERROR.getCode(), message);
    }


    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult runtimeExceptionHandler(RuntimeException e) {
        log.info("捕获到运行时异常 runtimeExceptionHandler:{}", e);
        return ResponseResult.failure(ErrorCodeEnum.UNKNOWN_ERROR.getCode(),
                e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public ResponseResult throwableHandler(Throwable th) {
        log.info("捕获到运行时异常 throwableHandler:{}", th);
        return ResponseResult.failure(ErrorCodeEnum.SYSTEM_ERROR.getCode(),
                th.getMessage());
    }
}
